package com.zhengb.algorithmdemo.leetcode.tree;


import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengbo
 * @date 2020/3/24
 */
public class ValidBinarySearchTree {

    public static void main(String[] args) {

        TreeNode root = new TreeNode(1);
        TreeNode left = new TreeNode(1);
//        TreeNode right = new TreeNode(3);

        root.left = left;
//        root.right = right;

        boolean validBST = new ValidBinarySearchTree().isValidBST(root);

        System.out.println(validBST);
    }

    private boolean isBinarySearchTree(TreeNode root, int preV) {
        if (root == null) {
            return true;
        }
        if (!isBinarySearchTree(root.left, preV)) {
            return false;
        }
        if (root.val < preV) {
            return false;
        }

        preV = root.val;
        return isBinarySearchTree(root.right, preV);

    }

    private void inOrderTraverseTree(TreeNode rootNode, List<Integer> list) {

        if (rootNode != null) {
            inOrderTraverseTree(rootNode.left, list);
            list.add(rootNode.val);
            inOrderTraverseTree(rootNode.right, list);
        }
    }

    public boolean isValidBST(TreeNode root) {

        List<Integer> inOrderTraverse = new ArrayList<>();
        inOrderTraverseTree(root, inOrderTraverse);

        for (int i = 0; i < inOrderTraverse.size() - 1; i++) {
            if (inOrderTraverse.get(i + 1) < inOrderTraverse.get(i)) {
                return false;
            }
        }
        return true;

    }
}
